package com.ibm.spatiotemp.server.framework.reponse;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.ibm.spatiotemp.server.datamodel.gpsdata.TSPoint;
import com.ibm.spatiotemp.server.datamodel.gpsdata.TSPointResultSet;
import com.ibm.spatiotemp.tools.DateParser;

public class ResponseFormatter {
	
	public static Logger logger = Logger.getLogger(ResponseFormatter.class);
	
	public static String result_body_format = "{\"datasize\": %d, \"data\":[%s]}";
	public static int down_sampling_interval = 1;
	
	/*{"t":"2014-01-01T00:00:00.000", "p":{"type": "Point","coordinates": [-50,53] }}*/
	public static String formatTSPointResultSet(TSPointResultSet result)
	{
		String result_body = "";
		
		int batchsize = 0;
		StringBuffer strbuf = new StringBuffer();
		TSPoint curpoint = null;
		
	try {
		while( (curpoint = result.getNext()) != null){
			++batchsize;
			if(batchsize == 1)
			{
				strbuf.append(curpoint.toJsonString());
			}
			else{
				if(batchsize % down_sampling_interval == 0)
					strbuf.append(","+curpoint.toJsonString());
			}
		}
		result.close();
	} catch (Exception e) {
		logger.error(e);
	}
		result_body = String.format(result_body_format, batchsize, strbuf.toString());
		return result_body;
	}
	
	public static String Trajectory_format =  "{"
	+ "\"id\": \"%s\","
	+ "\"sessionid\": \"%s\","
	+ "\"trajectory\": {"
	+ "\"type\": \"Linestring\","
	+ "\"coordinates\": [%s],"
	+ "\"times\": [%s]"
	+ "}"
	+ "}";
	// string[0]: cordinates String[1]:time
	public static String cordinate_format = "[%f,%f]";
	public static String date_format = "\"%s\"";
	public static Map<String,StringBuffer[]> formatTSPointResultSetAsMap(TSPointResultSet result)
	{
		//key modid, value: cordinate and date buffer
		Map<String, StringBuffer[]> resultmap = new HashMap<String, StringBuffer[]>();
		TSPoint curpoint = null;
		
		int i = 0;
		
		try {
			while( (curpoint = result.getNext()) != null){
				String modid = curpoint.tsid.trim();
				if(resultmap.containsKey(modid)){
					StringBuffer[] resultbufs = resultmap.get(modid);
					resultbufs[0].append(",");
					resultbufs[0].append(String.format(cordinate_format, curpoint.x,curpoint.y));
					resultbufs[1].append(",");
					resultbufs[1].append(String.format(date_format,DateParser.FormatDate(curpoint.time_stamp)));
				}
				else{
					StringBuffer[] resultbufs = new StringBuffer[2];
					resultbufs[0] = new StringBuffer();
					resultbufs[1] = new StringBuffer();
					resultbufs[0].append(String.format(cordinate_format, curpoint.x,curpoint.y));
					resultbufs[1].append(String.format(date_format,DateParser.FormatDate(curpoint.time_stamp)));
					
					if(i % down_sampling_interval == 0)/*down sampling*/
						resultmap.put(modid, resultbufs);
				}
				++i;
			}
			result.close();
		} catch (Exception e) {
			logger.error(e);
		}
		return resultmap;
	}
	
	public static String[] formatTSPointResultSetAsTimeandCoordinates(TSPointResultSet result)
	{
		//key modid, value: cordinate and date buffer
		Map<String, StringBuffer[]> resultmap = formatTSPointResultSetAsMap(result);
		if(!resultmap.keySet().isEmpty())
		{
			int idx = 0;
			String[] resultvector = new String[resultmap.keySet().size()];
			for (String id : resultmap.keySet()) {
				StringBuffer[] resultbufs = resultmap.get(id);
				resultvector[idx++] = String.format(Trajectory_format, id, result.getSessionID()!=null? result.getSessionID():"old_query", 
						resultbufs[0].toString(), resultbufs[1].toString());
			}
			return resultvector;
		}
		else
			return new String[]{""};
	}
	
	public static String TSPoint_format = 
			"{"
			+ "\"id\": \"%s\"," +
			"\"sessionid\":" +"\"%s\","
			+"\"trajectory\"" +": {"
			+"\"type\"" + ":\"Point\","
			+"\"coordinates\":" + "%s,"
			+"\"times\":" + "[%s]}"
			+ "}";
	
	public static String[] formatTSPointResultSetAsPoints(TSPointResultSet result)
	{
		//key modid, value: cordinate and date buffer
		Map<String, StringBuffer[]> resultmap = formatTSPointResultSetAsMap(result);
		if(!resultmap.keySet().isEmpty())
		{
			int idx = 0;
			String[] resultvector = new String[resultmap.keySet().size()];
			for (String id : resultmap.keySet()) {
				StringBuffer[] resultbufs = resultmap.get(id);
				resultvector[idx++] = String.format(TSPoint_format, id, result.getSessionID()==null? result.getSessionID():"old_query", 
						resultbufs[0].toString(), resultbufs[1].toString());
			}
			return resultvector;
		}
		else
			return new String[]{""};
	}
	
	public static String response_format = "{\"requesttype\": \"%s\", \"body\":%s}";
	public static String formatResponse(String req_type, String body){
		return String.format(response_format, req_type, body);
	}
	
	public static void main(String[] args){}
	
}
